/**
 * API客户端 v2 - 基于新架构的API调用封装
 */

import axios from 'axios'

// 创建axios实例
const apiClient = axios.create({
  timeout: 120000, // 2分钟超时，用于长时间操作
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log(`API请求: ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log(`API响应: ${response.status} ${response.config.url}`)
    return response
  },
  (error) => {
    console.error('API响应错误:', error.response?.data || error.message)
    
    // 统一错误处理
    const errorMessage = error.response?.data?.message || error.message || '请求失败'
    const errorCode = error.response?.data?.error_code
    
    return Promise.reject({
      message: errorMessage,
      code: errorCode,
      status: error.response?.status,
      originalError: error
    })
  }
)

/**
 * 智能更新API调用
 */
const intelligentUpdateApi = {
  // 步骤1: LWX平台数据解析
  async lwxParse(triggerSync = false) {
    const response = await apiClient.post('/api/intelligent-updates/v2/lwx-parse', {
      trigger_sync: triggerSync
    })
    return response.data
  },

  // 步骤2: 智能镜像版本校验
  async imageVerify(fullImageUrl, containerName) {
    const response = await apiClient.post('/api/intelligent-updates/v2/image-verify', {
      full_image_url: fullImageUrl,
      container_name: containerName
    })
    return response.data
  },

  // 步骤3: 条件性镜像拉取
  async conditionalPull(actionType, fullImageUrl) {
    const response = await apiClient.post('/api/intelligent-updates/v2/conditional-pull', {
      action_type: actionType,
      full_image_url: fullImageUrl
    })
    return response.data
  },

  // 步骤4: 智能容器重建
  async containerRebuild(actionType, containerName, fullImageUrl, schoolName) {
    const response = await apiClient.post('/api/intelligent-updates/v2/container-rebuild', {
      action_type: actionType,
      container_name: containerName,
      full_image_url: fullImageUrl,
      school_name: schoolName
    })
    return response.data
  },

  // 完整工作流执行
  async completeWorkflow(forceUpdate = false) {
    const response = await apiClient.post('/api/intelligent-updates/v2/complete-workflow', {
      force_update: forceUpdate
    })
    return response.data
  }
}

/**
 * 状态查询API调用
 */
const statusApi = {
  // 获取更新进度
  async getUpdateProgress() {
    const response = await apiClient.get('/api/status/update-progress')
    return response.data
  },

  // 获取系统信息
  async getSystemInfo() {
    const response = await apiClient.get('/api/status/system-info')
    return response.data
  },

  // 获取容器状态
  async getContainerStatus(containerName) {
    const response = await apiClient.get(`/api/status/container/${containerName}`)
    return response.data
  },

  // 健康检查
  async healthCheck() {
    const response = await apiClient.get('/api/status/health')
    return response.data
  }
}

/**
 * 配置管理API调用
 */
const configApi = {
  // 列出学校配置
  async listSchoolConfigs() {
    const response = await apiClient.get('/api/config/schools')
    return response.data
  },

  // 获取学校配置
  async getSchoolConfig(schoolName) {
    const response = await apiClient.get(`/api/config/schools/${encodeURIComponent(schoolName)}`)
    return response.data
  },

  // 保存学校配置
  async saveSchoolConfig(schoolName, configData) {
    const response = await apiClient.post(`/api/config/schools/${encodeURIComponent(schoolName)}`, configData)
    return response.data
  },

  // 获取当前学校信息
  async getCurrentSchool() {
    const response = await apiClient.get('/api/config/current-school')
    return response.data
  },

  // 设置当前学校信息
  async setCurrentSchool(schoolName, schoolId = '', baseImage = 'mobox-python-hardware:latest') {
    const response = await apiClient.post('/api/config/current-school', {
      school_name: schoolName,
      school_id: schoolId,
      base_image: baseImage
    })
    return response.data
  },

  // 获取模式匹配配置
  async getPatternMatchingConfig() {
    const response = await apiClient.get('/api/config/pattern-matching')
    return response.data
  },

  // 测试模式匹配
  async testPatternMatching(imageName) {
    const response = await apiClient.post('/api/config/pattern-matching/test', {
      image_name: imageName
    })
    return response.data
  }
}

/**
 * 长时间操作的API调用（扩展超时）
 */
const longTimeoutApi = {
  async post(url, data, timeout = 300000) { // 5分钟超时
    const response = await apiClient.post(url, data, { timeout })
    return response.data
  },

  async get(url, timeout = 300000) {
    const response = await apiClient.get(url, { timeout })
    return response.data
  }
}

// 导出
export default apiClient
export { 
  apiClient,
  intelligentUpdateApi,
  statusApi,
  configApi,
  longTimeoutApi
}